package com.meringer.beans;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.primefaces.event.RowEditEvent;

import com.meringer.beans.ejb.CarModelsEJB;
import com.meringer.entities.Car;
import com.meringer.entities.CarModel;

@ManagedBean(name = "tableCarModelBean")
@ViewScoped
public class TableCarModelBean {
	 @EJB
	CarModelsEJB carModelsEJB;

	private List<CarModel> allCarModels;

	public TableCarModelBean() {
		allCarModels = new ArrayList<CarModel>();
//		initCarModels();
	}
	
	@PostConstruct
	private void initCarModels() {
		System.out.println("ejbis " + carModelsEJB);
		allCarModels = carModelsEJB.getCarModels();
	}

	public List<CarModel> getAllCarModels() {
		return allCarModels;
	}

	public void setAllCarModels(List<CarModel> allCarModels) {
		this.allCarModels = allCarModels;
	}

	public void onEdit(RowEditEvent event) {
		CarModel carModel =  (CarModel) event.getObject();
		if(carModel.getModelID() == null) {
			System.out.println(carModel.getName());
//			carModel.setModelID(10);
			carModelsEJB.addCarModel(carModel);
		} else {
			System.out.println(carModel.getName());
			carModelsEJB.updateCarModel(carModel);
		} 
		
	}

	public void onCancel(RowEditEvent event) {
		// FacesMessage msg = new FacesMessage("Car Cancelled", ((CarModel)
		// event.getObject()).getName());
		// FacesContext.getCurrentInstance().addMessage(null, msg);
		System.out.println("delete car model "
				+ ((CarModel) event.getObject()).getName());
		carModelsEJB.removeCarModel( ((CarModel) event.getObject()).getModelID()  );		
	}
	
	public void add(ActionEvent event){
		System.out.println("addbuton");
		allCarModels.add(new CarModel());
	}
	
	@PostConstruct
	void initialiseSession() {
	    FacesContext.getCurrentInstance().getExternalContext().getSession(true);
	}
}
